package com.cater.sys.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSONObject;
import com.cater.annotation.SystemControllerLog;
import com.cater.common.PageResult;
import com.cater.query.CommonQuery;
import com.cater.query.UserQuery;
import com.cater.sys.entity.Dep;
import com.cater.sys.entity.Filestorage;
import com.cater.sys.entity.Role;
import com.cater.sys.entity.RoleUR;
import com.cater.sys.entity.User;
import com.cater.sys.service.DepService;
import com.cater.sys.service.FilestorageService;
import com.cater.sys.service.RoleService;
import com.cater.sys.service.UserService;
import com.cater.utils.MD5Util;
import com.cater.utils.StringUitl;
import com.cater.utils.UploadUtil;

/**
 * @描述:首页
 * @作者 :ShenDong
 * @创建日期 :2016年12月7日8:41
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	UserService userService;

	@Autowired
	RoleService roleService;

	@Autowired
	DepService depService;

	@Autowired
	private FilestorageService filestorageServiceImpl;// 文件上传

	/**
	 * 全部用户
	 *
	 * @return
	 */
	@RequestMapping(value = "/list")
	public String login_default() {
		return "sys/user/user_tb_list";
	}

	@ResponseBody
	@RequestMapping(value = "/getAll")
	@SystemControllerLog(description = "查看用户")
	/* @RequiresPermissions("user:view") */
	public PageResult<User> getAll(UserQuery userQuery, Integer userid, HttpServletRequest request) {
		if (userQuery.getFlag() == null) {
			userQuery.setFlag(false);
		}
		if (userid != null) {
			Dep dep = depService.getpidByuser(userid);
			if (dep != null) {
				/* userQuery.setFlag(true); */
				if (dep.getCompanyId() == 0) {
					userQuery.setFlag(true);
					userQuery.setDepid(dep.getDepId());
				} else {
					/* userQuery.setDepid(dep.getCompanyId()); */
					userQuery.setDepid(dep.getDepId());
				}
			}
		}
		return userService.findPageResult(userQuery);
	}

	@RequestMapping("/addView")
	public String addView(Integer depid, Model model, CommonQuery query) {
		List<Role> role = roleService.getAllCommon(query);
		List<Dep> listdep = depService.getdepBypid(0, query);
		List<Dep> listdeps = new ArrayList<Dep>();
		for (Dep dep : listdep) {
			List<Dep> listd = depService.getdepBypid(dep.getDepId(), query);
			listdeps.add(dep);
			listdeps.addAll(listd);
		}
		model.addAttribute("role", role);
		if (depid == null) {
			depid = -1;
		}
		Dep dep = depService.getByid(depid);
		model.addAttribute("depb", dep);
		model.addAttribute("dep", listdeps);
		model.addAttribute("depid", depid);
		return "sys/user/user_add";
	}

	@ResponseBody
	@RequestMapping("/add")
	@SystemControllerLog(description = "新增用户")
	public JSONObject add(User user, String roleIds, HttpServletRequest request) {
		user.setPassword(MD5Util.string2MD5(user.getPassword()));
		JSONObject json = new JSONObject();
		try {
			int id = userService.save(user);
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 一次遍历所有文件
				MultipartFile files = multiRequest.getFile("file");
				UploadUtil.fileUploads(null, files, user.getId() + "", "2", 1, request, filestorageServiceImpl);
			}
			int userId = user.getId();
			String[] v_ids = roleIds.split(",");
			for (String string : v_ids) {
				userService.saveUR(userId, StringUitl.getInteger(string));
			}
			json.put("code", 200);
			json.put("message", "添加成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "添加失败");
		}
		return json;
	}

	/**
	 * 打开修改页面
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/editView")
	public String editView(Integer id, Integer depid, Model model, CommonQuery query) {
		User users = userService.getByid(id);
		List<RoleUR> rolecake = roleService.getByUserId(id, query);
		List<Dep> listdep = depService.getdepBypid(0, query);
		List<Dep> listdeps = new ArrayList<Dep>();
		for (Dep dep : listdep) {
			List<Dep> listd = depService.getdepBypid(dep.getDepId(), query);
			listdeps.add(dep);
			listdeps.addAll(listd);
		}
		if (depid == null) {
			depid = -1;
		}
		Dep dep = depService.getByid(depid);
		model.addAttribute("depb", dep);
		model.addAttribute("dep", listdeps);
		model.addAttribute("depid", depid);
		model.addAttribute("users", users);
		model.addAttribute("rolecake", rolecake);
		return "sys/user/user_edit";
	}

	/**
	 * 修改用户
	 *
	 * @param user
	 * @param roleIds
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/edit")
	@SystemControllerLog(description = "用户修改")
	public JSONObject edit(User user, String roleIds, HttpServletRequest request) {
		User users = userService.getByid(user.getId());
		users.setUsername(user.getUsername());
		users.setTruename(user.getTruename());
		users.setMobile(user.getMobile());
		users.setEmail(user.getEmail());
		users.setDepid(user.getDepid());
		users.setDatarole(user.getDatarole());
		JSONObject json = new JSONObject();
		try {
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			if (multipartResolver.isMultipart(request)) {
				// 将request变成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 一次遍历所有文件
				MultipartFile files = multiRequest.getFile("file");
				if (files != null) {
					String realPath = request.getSession().getServletContext().getRealPath("/") + "static/upload/";
					List<Filestorage> list = filestorageServiceImpl.getAllByattributeId(users.getId() + "", "2");
					if (list != null && list.size() > 0) {
						Filestorage filestorage = filestorageServiceImpl
								.getById(String.valueOf(list.get(0).getFlieId()));
						File file = new File(realPath + filestorage.getFlieName());
						if (file.exists()) {
							file.delete();
						}
						filestorageServiceImpl.delete(filestorage.getFlieId());
					}
					UploadUtil.fileUploads(null, files, users.getId() + "", "2", 1, request, filestorageServiceImpl);
				}
			}
			userService.update(users);
			userService.deleteUR(user.getId());
			String[] v_ids = roleIds.split(",");
			for (String string : v_ids) {
				userService.saveUR(user.getId(), StringUitl.getInteger(string));
			}
			json.put("code", 200);
			json.put("message", "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "修改失败");
		}
		return json;
	}

	@ResponseBody
	@RequestMapping("/delete")
	@SystemControllerLog(description = "删除用户")
	public JSONObject delete(Integer id) {
		JSONObject json = new JSONObject();
		try {
			userService.delete(id);
			userService.deleteUR(id);
			json.put("code", 200);
			json.put("message", "删除成功！");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "删除失败！");
		}
		return json;
	}

	/**
	 * 查询用户名是否存在
	 *
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getbyname")
	public boolean getbyname(String name, Integer id) {
		User user = userService.findByName(name);
		User uu = null;
		if (id != null) {
			uu = userService.getByid(id);
		}

		if (user == null) {
			return true;
		}
		if (uu != null) {
			if (uu.getUsername().equals(name)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 打开修改密码页面
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/editpwdView")
	public String editpwdView(Integer id, Model model) {
		User users = userService.getByid(id);
		model.addAttribute("users", users);
		return "sys/user/user_editpwd";
	}

	/**
	 * 修改密码
	 *
	 * @param user
	 * @param roleIds
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/editpwd")
	@SystemControllerLog(description = "修改密码")
	public JSONObject editpwd(User user) {
		user.setPassword(MD5Util.string2MD5(user.getPassword()));
		JSONObject json = new JSONObject();
		try {
			userService.updatepaw(user);
			json.put("code", 200);
			json.put("message", "修改密码成功");
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 999);
			json.put("message", "修改密码失败");
		}
		return json;
	}

	/**
	 * 分配资源页面
	 */
	@RequestMapping(value = "/openZtree")
	public String openauth(HttpServletRequest request, Model model) {
		String ids = request.getParameter("ids");
		String types = request.getParameter("types");
		if (StringUtils.isNotBlank(ids)) {
			model.addAttribute("ids", ids);
		}
		String url = "";
		if (types.equals("redio")) {
			url = "sys/user/redio_user";
		} else {
			url = "sys/user/select_user";
		}
		return url;
	}

	/**
	 * 分配资源
	 */
	@ResponseBody
	@RequestMapping(value = "/getZtreeJson")
	public List<Map<String, Object>> getZtreeJson(HttpServletRequest request) {
		String ids = request.getParameter("ids");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		List<Dep> deps = depService.getAll();
		List<User> users = userService.getAll();
		Integer dep_id = 0;
		Integer user_id = 0;
		for (Dep t : deps) {
			map = new HashMap<String, Object>();
			dep_id = t.getDepId();
			map.put("id", "d" + dep_id);
			map.put("pId", "d" + t.getCompanyId());
			map.put("name", t.getDepName());
			map.put("nocheck", true);
			map.put("open", true);
			list.add(map);
			for (User user : users) {
				if (dep_id == user.getDep().getDepId()) {
					user_id = user.getId();
					map = new HashMap<String, Object>();
					map.put("id", user_id);
					map.put("pId", "d" + dep_id);
					map.put("name", user.getTruename());
					if (StringUtils.isNotEmpty(ids)) {
						String[] tid = ids.split(",");
						for (String id : tid) {
							if (user.getId().equals(Integer.valueOf(id))) {
								map.put("checked", true);
							}
						}

					}
					list.add(map);
				}
			}
		}
		return list;
	}

}
